package com.aiju.cash.ui.billing;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Good;
import com.aiju.cash.R;
import com.aiju.cash.ui.good.manager.GoodManager;
import com.aiju.cash.ui.good.manager.ShopCart;
import com.aiju.common.ImageLoader;
import com.aiju.common.db.GoodService;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.ShoppingView;
import com.aiju.widgit.dialog.EditWeighDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-12-14 13:58
 * @version: V1.0
 * @Description: 搜索商品界面
 */
public class SearchActivity extends BaseTitleActivity implements View.OnClickListener {

    private EditText mSearchEditText;
    private View mTipView, mDataView, mEmptyView;
    private ListView mListView;
    private TextView goodTipNum, goodPrice;
    /*
        private static ShopCartDialog shopCartDialog;*/
    private GoodService service;
    private List<Good> likeGood = new ArrayList<>();
    private GoodBaseAdapter adapter;

    private GoodManager goodManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        setCenterTitle("搜索商品");

        service = new GoodService(this);
        goodManager = GoodManager.getInstance(this);

        mSearchEditText = (EditText) findViewById(R.id.ev_search_good);
        mTipView = findViewById(R.id.ly_search_tip);
        mDataView = findViewById(R.id.ly_search_data);
        mEmptyView = findViewById(R.id.tv_search_empty);
        mListView = (ListView) findViewById(R.id.lv_search_good);

        goodTipNum = (TextView) findViewById(R.id.tv_biling_tip);
        goodPrice = (TextView) findViewById(R.id.tv_shop_money);
        findViewById(R.id.rl_billing_shop).setOnClickListener(this);

        setBottonView();
        goodManager.addOnChangeListener(new GoodManager.OnChangeListener() {
            @Override
            public void changeView() {
                setBottonView();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        });
        findViewById(R.id.rl_billing_shop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goodManager.isEmptySelectedGood()) {
                    T.ToastShort("购物车为空");
                    return;
                }
                goodManager.setShopCartDialog(new ShopCart(SearchActivity.this));
                goodManager.getShopCartDialog().setSystemAlert().show();
            }
        });
        findViewById(R.id.tv_billing_order).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goodManager.isEmptySelectedGood()) {
                    T.ToastShort("购物车为空");
                    return;
                }
                startActivity(OrderActivity.class);
            }
        });

        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mTipView.setVisibility(View.VISIBLE);
                    mDataView.setVisibility(View.GONE);
                    mEmptyView.setVisibility(View.GONE);
                } else {
                    mTipView.setVisibility(View.GONE);
                    mDataView.setVisibility(View.VISIBLE);
                    searchGood(s);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 设置底部购物车数据
     */
    private void setBottonView() {
        String totalSum = goodManager.getTotalSum();
        if (totalSum.equals("0")) {
            goodTipNum.setVisibility(View.GONE);
        } else {
            goodTipNum.setVisibility(View.VISIBLE);
        }
        goodTipNum.setText("" + totalSum);
        goodPrice.setText("" + goodManager.getTotalPrice());
    }


    private String search;

    /**
     * 根据输入的字符查找本地数据库
     *
     * @param s
     */
    private void searchGood(CharSequence s) {
        search = s.toString();
        change();
    }

    /**
     */
    private void change() {
        likeGood.clear();
        List<Good> goodgs = service.getLikeGood(search);
        for (Good good : goodManager.getGoods()) {
            for (Good good2 : goodgs) {
                if (good.getId().equals(good2.getId())) {
                    likeGood.add(good);
                }
            }
        }
        if (!Util.isEmpty(this.likeGood)) {
            if (adapter == null) {
                adapter = new GoodBaseAdapter(this, this.likeGood);
                mListView.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
        } else {//没有数据*/
            mDataView.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {

    }

    private final class GoodBaseAdapter extends BaseAdapter {

        private List<Good> goods;

        private Context context;

        public GoodBaseAdapter(Context context, List<Good> goods) {
            this.goods = goods;
            this.context = context;
        }

        @Override
        public int getCount() {
            return goods.size();
        }

        @Override
        public Object getItem(int position) {
            return goods.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.item_search_good, parent, false);
            final Good good = goods.get(position);
            TextView name = (TextView) inflate.findViewById(R.id.tv_good_name);
            TextView price = (TextView) inflate.findViewById(R.id.tv_good_price);
            TextView code = (TextView) inflate.findViewById(R.id.tv_good_code);
            ImageView pic = (ImageView) inflate.findViewById(R.id.iv_good_pic);

            name.setText(good.getName());
            code.setText(good.getCode());

            if (!Util.isEmpty(good.getImageUrl())) {
                ImageLoader.loadImage(pic, good.getImageUrl());
            }

            final ShoppingView shoppingView = (ShoppingView) inflate.findViewById(R.id.iv_good_select);
            if (good.isWeighGood()) {
                price.setText(good.getPrice() + "/" + good.getUnit());
                shoppingView.setShowWeigh(goodManager.getSelectedItemWeighById(good.getIntId()));
                shoppingView.getWeighTextView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new EditWeighDialog(context)
                                .setTitileText(good.getName())
                                .setMsgText(good.getPrice() + "/" + good.getUnit())
                                .setContentText(Util.clearZero(good.getWeigh()))
                                .setLayoutParams()
                                .setOnEditClick(new EditWeighDialog.OnEditClick() {
                                    @Override
                                    public void onCancel() {
                                        shoppingView.setSum(0);
                                    }

                                    @Override
                                    public void onSubmit(String msg) {
                                        if (TextUtils.isEmpty(msg)) {
                                            T.ToastShort("请输入商品重量");
                                            shoppingView.setSum(0);
                                            return;
                                        }
                                        good.setWeigh(Double.valueOf(msg));
                                        goodManager.update(true);
                                    }
                                })
                                .setCanceledOnTouchOutside(false).show();
                    }
                });
            } else {
                price.setText(good.getPrice());
                shoppingView.setSum(goodManager.getSelectedItemCountById(good.getIntId()));
            }
            shoppingView.setOnAmountChangeListener(new ShoppingView.OnAmountChangeListener() {
                @Override
                public void onAmountChange(int type, int sum) {
                    if (type == ShoppingView.ADD) {
                        if (good.isWeighGood()) {
                            new EditWeighDialog(context)
                                    .setTitileText(good.getName())
                                    .setMsgText(good.getPrice() + "/" + good.getUnit())
                                    .setLayoutParams()
                                    .setOnEditClick(new EditWeighDialog.OnEditClick() {
                                        @Override
                                        public void onCancel() {
                                            shoppingView.setSum(0);
                                        }

                                        @Override
                                        public void onSubmit(String msg) {
                                            if (TextUtils.isEmpty(msg)) {
                                                T.ToastShort("请输入商品重量");
                                                shoppingView.setSum(0);
                                                return;
                                            }
                                            good.setWeigh(Double.valueOf(msg));
                                            goodManager.add(good, true);
                                        }
                                    })
                                    .setCanceledOnTouchOutside(false).show();

                        } else {
                            goodManager.add(good, true);
                        }
                    } else {
                        goodManager.remove(good, true);
                    }
                }
            });

            return inflate;
        }
    }
}
